import { sport_data, sport_map } from '../../utils/dataset/db_data';
import { court_fields } from '../../utils/dataset/db_fields';
import { devDebug } from '../../utils/settings'

Page({
  data: {
    loading: 0,
    refresher: 0,
    actPopup: 0,
    submitLock: 0,
    courtId: '',
    stadium_id: '',
    sport_id: null,
    sport_name: '',
    court_name: '',
    court_price: null,
    sportList: sport_data,
    courtGroup: [],
    // 预约设置
    appointmentId: '',
  },
  onLoad(options) {
    if (devDebug) {
      options.appointmentId = '8f75309d6285fc4904584764552d958b-16529184';
      this.setData({ appointmentId: options.appointmentId })
      options.stadiumId = options.appointmentId.substring(0, options.appointmentId.lastIndexOf('-'));
      console.log(options.stadiumId);
    }
    this.setData({ stadium_id: options.stadiumId });
    if (!devDebug) this.onRefresh();
  },
  async onRefresh() {
    this.setData({ loading: 1 });
    let resList = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_court',
        data: {
          funcName: 'query',
          searchText: '',
          searchData: { stadium_id: this.data.stadium_id }
        },
        success: (r) => resolve(r.result),
      });
    });
    resList = resList.sort((a, b) => a.sport_id - b.sport_id);
    if (devDebug) console.log(resList);
    const courtGroup = [];
    let prev = -1;
    for (let i = 0; i < resList.length; i++) {
      const cur = resList[i].sport_id;
      if (prev !== cur) {
        courtGroup.push({
          title: sport_map.get(cur),
          courtList: [resList[i]]
        })
      } else {
        courtGroup[courtGroup.length - 1].courtList.push(resList[i])
      }
      prev = cur;
    }
    this.setData({ loading: 0, refresher: 0, courtGroup: courtGroup });
  },
  onSelectCourt(ev) {
    const _data = ev.currentTarget.dataset;
    this.onShowPopup();
    this.setData({
      courtId: _data.court_id,
      sport_name: sport_map.get(_data.sport_id),
      sport_id: _data.sport_id,
      court_name: _data.court_name,
      court_price: _data.court_price || null,
    });
  },
  onShowPopup() {
    this.setData({ courtId: '', sport_id: null, court_price: null, sport_name: '', court_name: '', actPopup: 1 })
  },
  onHidePopup() {
    this.setData({ actPopup: 0 })
  },
  onSelectSport(ev) {
    const sport_id = parseInt(ev.detail.value);
    this.setData({
      sport_id: sport_id,
      sport_name: this.data.sportList.filter(o => o._id == sport_id)[0].sport_name
    })
  },
  onPullDownRefresh() {
    this.onRefresh();
  },
  async onSubmit() {
    this.setData({ submitLock: 1 });
    const docData = {};
    court_fields.forEach(k => docData[k] = this.data[k]);
    if (docData.court_name !== '' && docData.sport_id !== null && docData.court_price !== null) {
      let _data = {};
      if (this.data.courtId) {
        _data.funcName = 'update';
        _data.court_id = this.data.courtId;
        _data.updData = docData;
      } else {
        _data.funcName = 'insert';
        _data.addData = docData;
      }
      const res = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_court',
          data: _data,
          success: (r) => resolve(r.result),
          fail: () => resolve()
        });
      })
      console.log(res);
      if ((this.data.courtId && !res) || (!this.data.courtId && res.errMsg)) {
        wx.showToast({ title: !res ? '操作失败，未知错误' : res.errMsg, icon: 'none' });
      } else {
        wx.showToast({ title: '操作成功' });
        this.onHidePopup();
      }
    } else {
      wx.showToast({ title: '字段不能为空', icon: 'none' });
    }
    this.setData({ submitLock: 0 });
    if (!devDebug) this.onRefresh();
  },
  async onDelete() {
    const confirm = await new Promise(resolve => {
      wx.showModal({
        title: '提示',
        content: '删除操作不可逆',
        success: (r) => resolve(r.confirm)
      })
    });
    if (confirm) {
      console.log(this.data.courtId);
      const res = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_court',
          data: {
            funcName: 'delete',
            rmData: { _id: this.data.courtId }
          },
          success: (r) => resolve(r.result),
          fail: () => resolve()
        });
      })
      console.log(res);
      if (res.errMsg) {
        wx.showToast({ title: res.errMsg, icon: 'none' });
      } else {
        wx.showToast({ title: '操作成功' });
        this.onHidePopup();
      }
    }
  }
})